import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
import { saveAs } from 'file-saver'
import { blobValidate, tansParams } from '@/common/uilts/ruoyi'
import errorCode from '@/common/uilts/errorCode'

let downloadLoadingInstance

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_URL, // api的base_url
  timeout: 5000 // 请求超时时间
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 可以在这里添加请求头等信息
    // 例如：config.headers['Authorization'] = 'Bearer your-token';
    // config.headers.Authorization = 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlbmFtZSI6ImFkbWluIiwidXNlcm5hbWUiOiJuYW1lIiwidXNlcmlkIjoiZjgzMzU1YzYtNzA4Yy00MjkyLTllYjMtODA0ODhiOWZkYjhkIiwiZXhwIjoxNzE1MDcxNTk1LCJpc3MiOiJkb3RuZXRzZXJ2ZXIiLCJhdWQiOiJkb3RuZXRzZXJ2ZXIifQ.Krh_0HF2kLMOq4RL7mh90oTo_X1CG8bEiKb0VuxPn_c'
    config.headers.Authorization = 'Bearer ' + localStorage.getItem('token')
    return config
  },
  error => {
    // 请求错误处理
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 对响应数据做处理，例如只返回data部分
    const res = response.data
    console.log('response :', response)
    // 根据后端返回的状态码进行处理，例如401未授权等

    return res
  },
  error => {
    // 响应错误处理
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)

// 通用下载方法
export function download (url, params, filename, config) {
  downloadLoadingInstance = ElLoading.service({ text: '正在下载数据，请稍候', background: 'rgba(0, 0, 0, 0.7)' })
  return service.post(url, params, {
    transformRequest: [(params) => { return tansParams(params) }],
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    responseType: 'blob',
    ...config
  }).then(async (data) => {
    const isBlob = blobValidate(data)
    if (isBlob) {
      const blob = new Blob([data])
      saveAs(blob, filename)
    } else {
      const resText = await data.text()
      const rspObj = JSON.parse(resText)
      const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode.default
      ElMessage.error(errMsg)
    }
    downloadLoadingInstance.close()
  }).catch((r) => {
    console.error(r)
    ElMessage.error('下载文件出现错误，请联系管理员！')
    downloadLoadingInstance.close()
  })
}

export default service
